package com.hyq.elasticsearchdemo.controller;

import com.hyq.elasticsearchdemo.dao.Hotel;
import com.hyq.elasticsearchdemo.utils.EsTemplate;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class testController {

    @Autowired
    private EsTemplate esTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("/createTest")
    public void createTest() throws Exception {
        Map<String, String> map = new HashMap();
        map.put("name", "keyword");
        map.put("score", "float");
        map.put("evaluate", "text");
        String test = esTemplate.createIndex("test","_doc", 2, 2, map);
        System.out.println(test);
    }

    @RequestMapping("/deleteTest")
    public void deleteTest() throws Exception {
        esTemplate.deleteIndex("test");
    }

    @RequestMapping("/existTest")
    public String existTest() throws Exception {
        boolean test = esTemplate.existIndex("test");
        return "test索引" + (test?"存在":"不存在");
    }

    @RequestMapping("/addDocument")
    public String addDocument() throws Exception {
        Hotel hotel = new Hotel();
        hotel.setName("如家");
        hotel.setScore(86.8F);
        hotel.setEvaluate("如家酒店评价较为优秀,环境干净整洁且隔音较好");
        String result = esTemplate.addDocument("test", hotel);
        return result;
    }

    @RequestMapping("/existDocument")
    public String existDocument() throws Exception {
        boolean test = esTemplate.existDocument("test","e19fc2e9-1eb6-4d84-92f5-a0fd2214265d");
        return "test索引中e19fc2e9-1eb6-4d84-92f5-a0fd2214265d文档" + (test?"存在":"不存在");
    }

    @RequestMapping("/updateDocument")
    public void updateDocument() throws Exception {
        Hotel hotel = new Hotel();
        hotel.setName("如家");
        hotel.setScore(88.8F);
        hotel.setEvaluate("如家酒店评价较为优秀,环境干净整洁且隔音较好");
        esTemplate.updateDocument("test","e19fc2e9-1eb6-4d84-92f5-a0fd2214265d",hotel);
    }

    @RequestMapping("/deleteDocument")
    public void deleteDocument() throws Exception {
        esTemplate.deleteDocument("test","e19fc2e9-1eb6-4d84-92f5-a0fd2214265d");
    }

    @RequestMapping("/getDocumentTrim")
    public void getDocumentTrim() throws Exception {
        SearchRequest searchRequest = new SearchRequest("test");
        //构建搜索的条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //创建一个query构造器,进行分组查询
        searchSourceBuilder.query(QueryBuilders.termQuery("name","如家"));
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        System.out.println("查询数量为:"+hits.getTotalHits().value);
        for (SearchHit hit : search.getHits()){
            System.out.println(hit.getSourceAsString());
        }
    }

    @RequestMapping("/getDocumentMatchHighlight")
    public String getDocumentMatchHighlight() throws Exception {
        String result = "";
        SearchRequest searchRequest = new SearchRequest("test");
        //构建搜索的条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        HighlightBuilder highlightBuilder = new HighlightBuilder();

        // 设置高亮样式及字段
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");

        //创建一个query构造器
        searchSourceBuilder.query(QueryBuilders.matchQuery("evaluate","干净"));
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        highlightBuilder.field(new HighlightBuilder.Field("evaluate"));
        searchSourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = search.getHits();
        System.out.println("查询数量为:"+hits.getTotalHits().value);
        for (SearchHit hit : search.getHits()){
            System.out.println(hit.getSourceAsString());

            Hotel hotel = JSON.parseObject(hit.getSourceAsString(), Hotel.class);

            //高亮信息输出
            HighlightField evaluate = hit.getHighlightFields().get("evaluate");
            Text content = evaluate.getFragments()[0];

            result += hotel.getName() + "评价为:" + content + "\n";
        }
        return result;
    }
}
